<?php

namespace app\api\controller\v1;



use app\admin\model\BdOrg;
use app\admin\model\Intentionorderentry;
use app\admin\model\Materialimage;
use app\admin\model\Ordercar;

use app\admin\model\Surface;
use think\Cache;

class Intentionorder extends Base
{

    //列表
    public function listIntentionorder()
    {
        $page                       = $this->params['page'] ?? 1;

        $map                        = [];
        $ordertype                  = !empty($this->params['ordertype']) ? $this->params['ordertype'] : [];//1期货 2现货
        $orderstatus                = !empty($this->params['orderstatus']) ? $this->params['orderstatus'] : [];//1=待确认；2=已确认；'
        $keyword                    = !empty($this->params['keyword']) ? $this->params['keyword'] : [];
        $time                       = !empty($this->params['time']) ? $this->params['time'] : [];


        $cacheTag       = \config('cache_tag')['v1_Intentionorder_listIntentionorder'];
        $cacheKey       = $cacheTag. $this->datacenter . $this->forgid . json_encode($page) . json_encode($ordertype) . json_encode($orderstatus) . json_encode($keyword) . json_encode($time);

        $data         =  Cache::get($cacheKey);

        if(!$data)
        {
            //组装查询条件
            if(!empty($ordertype))
            {
                $map['fk_bdl_ordertype'] = $ordertype;
            }

            if(!empty($orderstatus))
            {
                $map['fk_bdl_orderstatus'] = $orderstatus;
            }

            if(!empty($keyword))
            {
                $map['fk_bdl_wxbillno'] = ['like',"%{$keyword}%"];
            }
            if(!empty($time))
            {
                $time = explode('~',$time);
                $map['fk_bdl_ordertime'] = ['between time',[$time[0] . "00:00:00",$time[1] . "23:59:59"]];
            }

            $map['forgid']                                  = $this->forgid;
            $map['fk_bdl_bd_datacenter']                    = $this->datacenter;
//            $map['fk_bdl_userid']                           = $this->user_id;
            $map['fk_bdl_bd_customer']                      = $this->customer_id;

            //结束

            $data = \app\admin\model\Intentionorder::with(['orderentrynew'=>function($query){
                $query->where('forgid','in',$this->forgids);
            },'orderent'])
                ->where($map)->order('id', 'desc')
                ->page($page, $this->pageSize)
//                ->where('fk_bdl_bd_customer',$this->customer_id)
                ->where('fenable',"1")
                ->select()
                ->each(function($a){
                    $a['fk_bdl_allqty'] = floatval($a['fk_bdl_allqty']);
                });

            //组装数据
            $new_data = [];

            foreach($data as $v)
            {
                $show_mes = [
                    'order'             => $v['fk_bdl_wxbillno'],
                    'order_time'        => $v['fk_bdl_ordertime'],
                    'order_type'        => $v['fk_bdl_ordertype'],
                    'fk_bdl_image'      => $v['fk_bdl_image'],
                    'order_status'      => $v['fk_bdl_orderstatus'],
                    'fk_bdl_confirmtime'=> $v['fk_bdl_confirmtime'],
                    'fk_bdl_allamount'  => $v['fk_bdl_allamount'],
                    'fk_bdl_comment'    => $v['fk_bdl_comment'],
                    'id'                => $v['id'],
                    'qty'               => $v['fk_bdl_allqty']
                ];

                //判断不同订单展示不同数据
                if($v['fk_bdl_ordertype'] == 1)
                {
                    // 准备一个数组来存储分组后的数据
                    $groupedInfos = [];

                    foreach ($v['orderent'] as $infoson)
                    {
                        $infoson['fk_bdl_qty'] = floatval($infoson['fk_bdl_qty']);
                        $fk_bdl_bd_surface = $infoson['fk_bdl_bd_surface'];

                        if (!isset($groupedInfos[$fk_bdl_bd_surface])) {
                            $groupedInfos[$fk_bdl_bd_surface] = [];
                        }

                        $groupedInfos[$fk_bdl_bd_surface][] = $infoson->toArray();
                    }
                    $mater = [];

                    foreach ($groupedInfos as $kk=>$vv)
                    {
                        $surface = $kk;
                        $surface = Surface::where('fname',$surface)
                            ->where('forgid','in',$this->forgids)
                            ->find();
                        if(!empty($surface))
                        {
                            $surfaceI = Materialimage::where('fk_bdl_bd_surface',$surface['id'])
                                ->find();

                            if(!empty($surfaceI))
                            {
                                $showImageUrl = $surfaceI['fk_bdl_imageurl'];
                            }else{
                                $showImageUrl = $this->getDefaultImage();
                            }
                        }else{
                            $showImageUrl = $this->getDefaultImage();
                        }

                        $mater[] = [
                            'fk_bdl_bd_surface' => $kk,
                            'fk_bdl_bd_texture' =>$vv[0]['fk_bdl_bd_texture'],
                            'show_image'        => $showImageUrl,
                            'infos' => $vv
                        ];
                    }
                    $show_mes['mater'] = $mater;

                }else{
                    $mater = [];
                    if(!empty($v['orderentrynew']) || is_array($v['orderentrynew']) || is_object($v['orderentrynew']))
                    {
                        if(!is_null($v['orderentrynew']) && !$v['orderentrynew']->isEmpty())
                        {
                            foreach ($v['orderentrynew'] as $kk => $vv)
                            {
                                $show = [];
                                foreach ($vv['inventoryone']['inventoryentryvalue'] as $kkk => $vvv)
                                {
                                    if(in_array($vvv['fnumber'],['bdl_thickness','bdl_width','bdl_length','bdl_refthickness','bdl_materialgrade']))
                                    {
                                        $show[$vvv['fnumber']] = $vvv['pivot']['fk_bdl_matpropvalue'];
                                    }
//                            if(in_array($vvv['fnumber'],['bdl_thickness','bdl_width','bdl_length','bdl_refthickness']))
//                            {
//                                switch ($vvv['fnumber'])
//                                {
//                                    case "bdl_thickness":
//                                        $sort = 1;
//                                        break;
//                                    case "bdl_length":
//                                        $sort = 3;
//                                        break;
//                                    case "bdl_width":
//                                        $sort = 2;
//                                        break;
//                                    case "bdl_refthickness":
//                                        $sort = 4;
//                                        break;
//                                }
//                                $inventory[$vvv['fnumber']] = [
//                                    'name'      => $vvv['fname'],
//                                    'value'     => floatval($vvv['pivot']['fk_bdl_matpropvalue']),
//                                    'unit'      => $vvv['fk_bdl_unit'],
//                                    'fnumber'   => $vvv['fnumber'],
//                                    'sort'      => $sort
//                                ];
//                            }
                                }

                                //排序
//                        usort($inventory, function($a, $b) {
//                            return $a['sort'] - $b['sort'];
//                        });


                                $surface_id     = $vv['inventoryone']['fk_bdl_bd_surface'];
                                $material_id    =  $vv['material']['id'];
                                if(!empty($surface_id) && !empty($material_id))
                                {
                                    $find       = Materialimage::where('fk_bdl_bd_surface',$surface_id)->where('fk_bdl_bd_material',$material_id)->find();
                                    if(!empty($find))
                                    {
                                        $show_image = $find['fk_bdl_imageurl'];
                                    }else{
                                        $show_image = $this->getDefaultImage();
                                    }
                                }else{
                                    $show_image = $this->getDefaultImage();
                                }


                                $mater[$kk] = [
                                    'name'                  => $vv['material']['fname'],
                                    'unitid'                => $vv['material']['fk_bdl_unitid'],
                                    'fk_bdl_priceunitid'    => $vv['material']['fk_bdl_priceunitid'],
                                    'qty'                   => $vv['fk_bdl_qty'],
                                    'value'                 => $show,
                                    'surface'               => $vv['inventoryone']['surfaceone']['fname'],
                                    'texture'               => $vv['inventoryone']['textureone']['fname'],
                                    'show_image'            => $show_image,
                                ];
                            }
                        }
                    }

                    $show_mes['mater'] = $mater;
                }

                $new_data[] = $show_mes;
            }

            $data = $new_data;

            Cache::tag($cacheTag)->set($cacheKey,$data,$this->cacheExpire);

        }


        $this->success('',$data);

    }

    //现货
    public function placeIntentionorderX()
    {
        $check      = $this->plulicValidate($this->params,['fk_bdl_bd_useraddress|地址ID','orderentry|产品库存数据'],['require','require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }

        $forg       = BdOrg::get($this->forgid);
        $orderNo    = makeMiNiOrderNo('WXXH',$forg['fnumber']);


        //组装订单基本数据
        $data        = [
            'fk_bdl_comment'        => !empty($this->params['fk_bdl_comment']) ? $this->params['fk_bdl_comment'] : ' ',

            'fk_bdl_bd_useraddress'     => $this->params['fk_bdl_bd_useraddress'],
            'fk_bdl_wxbillno'           => $orderNo,
            'fk_bdl_userid'             => $this->user_id,
            'forgid'                    => $this->forgid,
            'fk_bdl_bd_customer'                    => $this->customer_id,
            'fk_bdl_ordertype'          => 2,
            'fk_bdl_bd_datacenter'      => $this->datacenter,
            'fk_bdl_ordertime'          => date('Y-m-d H:i:s')
        ];

        $res         = \app\admin\model\Intentionorder::create($data);

        if($res && $id = $res->id)
        {
            //订单添加成功后 将子订单id定义为关联主键
            $orderentry                = json_decode(html_entity_decode($this->params['orderentry']),true);

            $count                     = [];

            foreach ($orderentry as $k => $v)
            {
                $enteys = [
                    'id'                    => $id,
                    'forgid'                => $this->forgid,
                    'fk_bdl_bd_datacenter'  => $this->datacenter,
                    'fk_bdl_qty'            => $v['fk_bdl_qty'],
                    'fk_bdl_bd_material'    => $v['fk_bdl_bd_material'],
                    'fk_bdl_inventoryid'    => $v['fk_bdl_inventoryid'],
                ];
                Intentionorderentry::create($enteys);

                $count[] = $v['fk_bdl_qty'];
            }
            $count = array_sum($count);

            \app\admin\model\Intentionorder::where('id',$id)->update(['fk_bdl_allqty'=>$count]);

        }else{
            $this->error('下单失败');
        }

        //如果是从采购单下的订单 删除采购单数据
        if(!empty($this->params['type']) && $this->params['type'] == 1 && !empty($this->params['ids']))
        {
            $res    = Ordercar::where('id','in',$this->params['ids'])->select();

            foreach ($res as $item) {
                $item->delete();
            }
        }


        $cacheTag       = \config('cache_tag')['v1_Intentionorder_listIntentionorder'];
        Cache::tag($cacheTag)->clear();
        $this->success('下单成功',[
            'orderId'       => $id,
        ]);
    }

    //期货
    public function placeIntentionorderQ()
    {
        $check      = $this->plulicValidate($this->params,
            ['fk_bdl_bd_useraddress|发货地址','fk_bdl_bd_material_g|产品分组ID','fk_bdl_matpropvalue|产品属性json','fk_bdl_bd_texture|材质','fk_bdl_bd_surface|表面','fk_bdl_allqty|总数量'],
            ['require','require','require','require','require','require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }

        $fk_bdl_matpropvalue                = json_decode(html_entity_decode($this->params['fk_bdl_matpropvalue']),true);

        $order                              = makeMiNiOrderNo('WXDZ',BdOrg::get($this->forgid)['fnumber']);
        //组装期货数据
        $data      = [
            'fk_bdl_bd_material_g'      => $this->params['fk_bdl_bd_material_g'],
            'fk_bdl_bd_texture'         => $this->params['fk_bdl_bd_texture'],
            'fk_bdl_bd_surface'         => $this->params['fk_bdl_bd_surface'],
            'fk_bdl_matpropvalue'       => json_encode($fk_bdl_matpropvalue),
            'fk_bdl_allqty'             => $this->params['fk_bdl_allqty'],



            'fk_bdl_comment'            => !empty($this->params['fk_bdl_comment'])  ? $this->params['fk_bdl_comment'] : '',
            'fk_bdl_bd_useraddress'     => $this->params['fk_bdl_bd_useraddress'],
            'fk_bdl_wxbillno'           => $order,
            'fk_bdl_userid'             => $this->user_id,
            'fk_bdl_bd_customer'                    => $this->customer_id,
            'forgid'                    => $this->forgid,
            'fk_bdl_ordertype'          => 1,
            'fk_bdl_bd_datacenter'      => $this->datacenter,
            'fk_bdl_ordertime'          => date('Y-m-d H:i:s')
        ];

        $res       = \app\admin\model\Intentionorder::create($data);


        if(!$res)
        {
            $this->error('下单失败');
        }

        $cacheTag       = \config('cache_tag')['v1_Intentionorder_listIntentionorder'];
        Cache::tag($cacheTag)->clear();

        $this->success('下单成功',$res['id']);
    }

    public function cancel()
    {
        $check = $this->plulicValidate($this->params, ['id|ID'], ['require']);

        if ($check['code'] == 1) {
            $this->error($check['msg']);
        }
        //判断是否已经存在
        $isset = \app\admin\model\Intentionorder::where(['id' => $this->params['id']])->find();

        if (!$isset) {
            $this->error('信息错误');
        }

        $res = \app\admin\model\Intentionorder::where('id', $this->params['id'])->delete();

        if ($res)
        {
            $cacheTag       = \config('cache_tag')['v1_Intentionorder_listIntentionorder'];

            Cache::tag($cacheTag)->clear();

            $this->success('操作成功');
        }

        $this->error('操作失败');
    }

}